{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "google",
   "metadata": {},
   "source": [
    "##### Copyright 2025 Google LLC."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "apache",
   "metadata": {},
   "source": [
    "Licensed under the Apache License, Version 2.0 (the \"License\");\n",
    "you may not use this file except in compliance with the License.\n",
    "You may obtain a copy of the License at\n",
    "\n",
    "    http://www.apache.org/licenses/LICENSE-2.0\n",
    "\n",
    "Unless required by applicable law or agreed to in writing, software\n",
    "distributed under the License is distributed on an \"AS IS\" BASIS,\n",
    "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
    "See the License for the specific language governing permissions and\n",
    "limitations under the License.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "basename",
   "metadata": {},
   "source": [
    "# p_median"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "link",
   "metadata": {},
   "source": [
    "<table align=\"left\">\n",
    "<td>\n",
    "<a href=\"https://colab.research.google.com/github/google/or-tools/blob/main/examples/notebook/contrib/p_median.ipynb\"><img src=\"https://raw.githubusercontent.com/google/or-tools/main/tools/colab_32px.png\"/>Run in Google Colab</a>\n",
    "</td>\n",
    "<td>\n",
    "<a href=\"https://github.com/google/or-tools/blob/main/examples/contrib/p_median.py\"><img src=\"https://raw.githubusercontent.com/google/or-tools/main/tools/github_32px.png\"/>View source on GitHub</a>\n",
    "</td>\n",
    "</table>"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "doc",
   "metadata": {},
   "source": [
    "First, you must install [ortools](https://pypi.org/project/ortools/) package in this colab."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "install",
   "metadata": {},
   "outputs": [],
   "source": [
    "%pip install ortools"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "description",
   "metadata": {},
   "source": [
    "\n",
    "\n",
    "  P-median problem in Google CP Solver.\n",
    "\n",
    "  Model and data from the OPL Manual, which describes the problem:\n",
    "  '''\n",
    "  The P-Median problem is a well known problem in Operations Research.\n",
    "  The problem can be stated very simply, like this: given a set of customers\n",
    "  with known amounts of demand, a set of candidate locations for warehouses,\n",
    "  and the distance between each pair of customer-warehouse, choose P\n",
    "  warehouses to open that minimize the demand-weighted distance of serving\n",
    "  all customers from those P warehouses.\n",
    "  '''\n",
    "\n",
    "  Compare with the following models:\n",
    "  * MiniZinc: http://hakank.org/minizinc/p_median.mzn\n",
    "  * Comet: http://hakank.org/comet/p_median.co\n",
    "\n",
    "  This model was created by Hakan Kjellerstrand (hakank@gmail.com)\n",
    "  Also see my other Google CP Solver models:\n",
    "  http://www.hakank.org/google_or_tools/\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "code",
   "metadata": {},
   "outputs": [],
   "source": [
    "import sys\n",
    "from ortools.constraint_solver import pywrapcp\n",
    "\n",
    "\n",
    "def main():\n",
    "\n",
    "  # Create the solver.\n",
    "  solver = pywrapcp.Solver('P-median problem')\n",
    "\n",
    "  #\n",
    "  # data\n",
    "  #\n",
    "  p = 2\n",
    "\n",
    "  num_customers = 4\n",
    "  customers = list(range(num_customers))\n",
    "  Albert, Bob, Chris, Daniel = customers\n",
    "  num_warehouses = 3\n",
    "  warehouses = list(range(num_warehouses))\n",
    "  Santa_Clara, San_Jose, Berkeley = warehouses\n",
    "\n",
    "  demand = [100, 80, 80, 70]\n",
    "  distance = [[2, 10, 50], [2, 10, 52], [50, 60, 3], [40, 60, 1]]\n",
    "\n",
    "  #\n",
    "  # declare variables\n",
    "  #\n",
    "  open = [solver.IntVar(warehouses, 'open[%i]% % i') for w in warehouses]\n",
    "  ship = {}\n",
    "  for c in customers:\n",
    "    for w in warehouses:\n",
    "      ship[c, w] = solver.IntVar(0, 1, 'ship[%i,%i]' % (c, w))\n",
    "  ship_flat = [ship[c, w] for c in customers for w in warehouses]\n",
    "\n",
    "  z = solver.IntVar(0, 1000, 'z')\n",
    "\n",
    "  #\n",
    "  # constraints\n",
    "  #\n",
    "  z_sum = solver.Sum([\n",
    "      demand[c] * distance[c][w] * ship[c, w]\n",
    "      for c in customers\n",
    "      for w in warehouses\n",
    "  ])\n",
    "  solver.Add(z == z_sum)\n",
    "\n",
    "  for c in customers:\n",
    "    s = solver.Sum([ship[c, w] for w in warehouses])\n",
    "    solver.Add(s == 1)\n",
    "\n",
    "  solver.Add(solver.Sum(open) == p)\n",
    "\n",
    "  for c in customers:\n",
    "    for w in warehouses:\n",
    "      solver.Add(ship[c, w] <= open[w])\n",
    "\n",
    "  # objective\n",
    "  objective = solver.Minimize(z, 1)\n",
    "\n",
    "  #\n",
    "  # solution and search\n",
    "  #\n",
    "  db = solver.Phase(open + ship_flat, solver.INT_VAR_DEFAULT,\n",
    "                    solver.INT_VALUE_DEFAULT)\n",
    "\n",
    "  solver.NewSearch(db, [objective])\n",
    "\n",
    "  num_solutions = 0\n",
    "  while solver.NextSolution():\n",
    "    num_solutions += 1\n",
    "    print('z:', z.Value())\n",
    "    print('open:', [open[w].Value() for w in warehouses])\n",
    "    for c in customers:\n",
    "      for w in warehouses:\n",
    "        print(ship[c, w].Value(), end=' ')\n",
    "      print()\n",
    "    print()\n",
    "\n",
    "  print('num_solutions:', num_solutions)\n",
    "  print('failures:', solver.Failures())\n",
    "  print('branches:', solver.Branches())\n",
    "  print('WallTime:', solver.WallTime(), 'ms')\n",
    "\n",
    "\n",
    "main()\n",
    "\n"
   ]
  }
 ],
 "metadata": {
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
